package com.southminority.ethnic.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.southminority.ethnic.common.context.UserContext;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * 管理员权限验证拦截器
 * 用于验证访问/admin路径的用户是否为管理员（user_type != 0）
 * 
 * @author SouthMinority
 */
@Slf4j
@Component
public class AdminAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("=== 管理员权限拦截器开始执行 ===");
        
        // 获取请求路径
        String requestPath = request.getRequestURI();
        log.info("请求路径: {}", requestPath);
        
        // 只拦截/admin路径下的请求
        if (
                !requestPath.startsWith("/admin")&&
                !requestPath.startsWith("/vipadmin")&&
                !requestPath.startsWith("/aliyunOss")

                ) {
            log.info("非admin路径，跳过权限验证: {}", requestPath);
            return true;
        }

        log.info("开始验证admin路径权限: {}", requestPath);

        try {
            // 获取当前用户信息
            User currentUser = UserContext.getCurrentUser();
            log.info("当前用户信息: {}", currentUser);
            
            if (currentUser == null) {
                log.warn("访问管理员接口但用户未登录: {}", requestPath);
                sendForbiddenResponse(response, "用户未登录");
                return false;
            }

            log.info("用户ID: {}, 用户名: {}, 用户类型: {}", 
                currentUser.getId(), currentUser.getUsername(), currentUser.getUserType());

            // 检查用户类型，只有user_type != 0的用户才能访问
            if (currentUser.getUserType() == null || currentUser.getUserType() == 0) {
                log.warn("普通用户尝试访问管理员接口，用户ID: {}, 用户类型: {}, 路径: {}", 
                    currentUser.getId(), currentUser.getUserType(), requestPath);
                sendForbiddenResponse(response, "权限不足，需要管理员权限");
                return false;
            }
            //验证vip权限
            else if (requestPath.startsWith("/vipadmin")) {
                if (currentUser.getUserType() != 2) {
                    log.warn("普通用户尝试访问vip管理员接口，用户ID: {}, 用户类型: {}, 路径: {}",
                        currentUser.getId(), currentUser.getUserType(), requestPath);
                    sendForbiddenResponse(response, "权限不足，需要vip管理员权限");
                    return false;
                }
            }

            log.info("管理员权限验证通过，用户ID: {}, 用户类型: {}, 路径: {}", 
                currentUser.getId(), currentUser.getUserType(), requestPath);
            return true;

        } catch (Exception e) {
            log.error("管理员权限验证异常", e);
            sendForbiddenResponse(response, "权限验证失败：" + e.getMessage());
            return false;
        }
    }

    /**
     * 发送禁止访问响应
     */
    private void sendForbiddenResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        
        R<Void> result = R.fail(403, message);
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
} 